var textInput;
var fileInput = `<div class="file-input" tabindex="0"></div>`;
var questionInput;

var maxFileSize = 62914560;
// 全局文件数组，保存用户添加的文件
var fileArray = [];
// 全局已发送文件数组，保存已发送的文件，用于当文件发送失败时进行重新发送
var sendFileArray = [];
var msgPageIndex = 1;
var wsUrl = "";

var msgCount = 0;
var selectedChatRoomDom = null;


/**
 * 获取实时时间
 * */
function getDateTime(len=19) {
    let curDate = new Date();  //获取当前时间
    let year = curDate.getFullYear();  //获取年份
    let month = curDate.getMonth() + 1;  //获取月份
    let day = curDate.getDate();  //获取日期
    let hour = curDate.getHours();  //获取小时
    let minute = curDate.getMinutes();  //获取分钟
    let second = curDate.getSeconds();  //获取秒钟

//调整时间格式
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    hour = hour < 10 ? "0" + hour : hour;
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;

    let dataTime = (year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second).substring(0, len);

    return dataTime;
}

/**
 * 获取时间 写入user-info
 * */

$('.user-info').text(`最近上线时间：${getDateTime()}`)

//消息显示框
cocoMessage.config({
    //消息显示时长
    duration: 2000,
});

/**
 * 获取cookie
 * */
function getCookie(name) {
    //获取当前文档的cookie数组
    let cookieArr = document.cookie.split(";");
    for(let i = 0; i < cookieArr.length; i++) {
        //等号切割cookie
        let cookiePair = cookieArr[i].split("=");
        //如果获取的是“token”
        if(name === cookiePair[0].trim()) {
            //对token的值进行解码 获得对应的URL
            return decodeURIComponent(cookiePair[1]);
        }
    }
    return "";
}


//连接 以房间号为连接
let ws = null;

/**
 * 连接
 * */
function connect(room) {
    if (ws != null) {
        ws.close(1000, '切换讨论室')
    }
    // 获取 token，用于websocket连接认证
    let token = getCookie("token");
    //建立新的ws连接  wsUrl为“”此时
    ws = new WebSocket(`${wsUrl}${room}?token=${token}`);

    //建立连接
    ws.onopen = function() {
        console.log(`讨论室-->${room}: 连接已经建立`);
        cocoMessage.success(2000, `讨论室-->${room}: 连接已经建立`)
    };

    //发送消息
    ws.onmessage = function(evt) {
        acceptMsg(evt.data)
    };

    ws.onerror = function() {
        console.log('websocket 服务器异常')
        cocoMessage.error(2000, "websocket 服务器异常")
        // 重定向到登录页
        window.location.href = '/loginPage';
    };

    ws.onclose = function(evt) {
        if (evt.reason === '切换讨论室') {
            console.log(`讨论室-->${room}: 关闭当前连接`);
        } else {
            // 重定向到登录页
            window.location.href = '/loginPage';
        }
    };
}

/**
 *
 * 获取用户信息
 * */
$.ajax({
    url: '/getUserInfo/',
    type: 'post',
    contentType: false,
    processData: false,
    success: function (res) {
        if (res.code === 200) {
            let userInfoHtml = `${res.data.username}<span class="append-info" title="${res.data.code}">${res.data.code}</span>`
            $('.user-name').html(userInfoHtml);
            wsUrl = res.data.wsUrl;
            res.data.rooms.forEach(data => {
                let formattedDatetime = data.createTime.replace('T', ' ').substr(0, 19);
                $('.item-box').append(`<div class="chat-item">
                                <div class="chat-del"></div>
                                <div class="chat-title">${data.roomName}</div>
                                <div class="chat-bottom">
                                    <div class="chat-time">${formattedDatetime}</div>
                                    <div class="chat-num">0 条对话</div>
                                </div>
                            </div>`);
            })
        } else {
            // 重定向到登录页
            window.location.href = '/loginPage';
        }
    }
});


/**
 * 调用文心一言大模型
 * */
function WenXinModal(sendMessage,roomName){
    console.info("智能问答运行")
    let formData = new FormData();
    formData.append("message", sendMessage);
    formData.append("roomName",roomName);
    $.ajax({
        url: '/IntelligentAnswer/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                let answerMsg = res.data;
                sendAnswer(answerMsg);
            } else {
                // 重定向到登录页
               alert("智能问答失败");
            }
        }
    });
}


/**
 * 调用主题检测
 * */
function TopicDetection(sendMessage,roomName){
    console.info("主题检测运行")
    let formData = new FormData();
    formData.append("message", sendMessage);
    formData.append("roomName",roomName);
    $.ajax({
        url: '/TopicDetection/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                console.info("主题检测结果："+res.data);
                //如果没有偏题则继续进行问题检测
                if(res.data.includes("未偏题")){
                    isQuestion(sendMessage,roomName);
                }else{
                    //偏题了发送干预信息
                    sendAnswer(res.data);
                }
            } else {
                alert("主题检测失败");
            }
        }
    });
}



/**
 * 发送回答信息
 * */
function sendAnswer(answerMsg) {
    let user = "文文";
    let code = "2020213710";
    let sendType = 'answer';
    let sendAnswer = "@answer@"+answerMsg;
    let file = '';
    let thisBubble = drawBubble('left', 'end', user, code,  answerMsg, sendType, file)
    $('.text-input').val('');
    // todo 向websocket发送请求
    websocketSend(sendAnswer, thisBubble);
    // 发消息后滚动到最底部
    $('.right-chatRoom').animate({scrollTop:$('.right-chatRoom').prop('scrollHeight')}, 'slow');
}

/**
 * 批量导入用户
 * */

$('#insert-users').click(function () {
    showInsertModel();
})


$('#insert-course').click(function () {
    console.info("点击了新增课程");
    showInsertCourseModel();
})

$('#insert-course-student').click(function () {
    showInsertCourseStudentModel();
})
/**
 * 删除用户
 * */

$('#query-delete').click(function () {
    let name = $('#query-user-result-table').find('td').eq(0).text();
    let code = $('#query-user-result-table').find('td').eq(1).text();
    let formData = new FormData();
    console.log("删除用户");
    console.log(name,code);
    formData.append("name", name);
    formData.append("code",code);
    deleteUser(formData);
    $('#query-user-result').css('visibility','hidden');
})


/**
 * 删除课程
 * */

$('#query-delete-course').click(function () {
    let name = $('#query-course-result-table').find('td').eq(0).text();
    let teacher = $('#query-course-result-table').find('td').eq(1).text();
    let formData = new FormData();
    console.log("删除课程");
    console.log(name,teacher);
    formData.append("name", name);
    formData.append("teacher",teacher);
    deleteCourse(formData);
    $('#query-course-result').css('visibility','hidden');
})


/**
 * 删除课程-学生
 * */

$('#query-delete-course-student').click(function () {
    let studentCode = $('#query-course-student-result-table').find('td').eq(0).text();
    let courseCode = $('#query-course-student-result-table').find('td').eq(2).text();
    let formData = new FormData();
    console.log("删除-学生课程");
    console.log(studentCode,courseCode);
    formData.append("studentCode", studentCode);
    formData.append("courseCode",courseCode);
    deleteCourseStudent(formData);
    $('#query-course-result').css('visibility','hidden');
})

function deleteUser(formData){
    console.info(formData.name);
    console.info(formData.code);
    $.ajax({
        url: '/deleteUser/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                cocoMessage.success(2000,"删除用户成功");
                console.info(formData.name,formData.code);
            } else {
                cocoMessage.error(2000,"删除用户失败");
            }
        }
    });
}

function deleteCourse(formData){
    console.info(formData.name);
    console.info(formData.teacher);
    $.ajax({
        url: '/deleteCourse/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                cocoMessage.success(2000,"删除用户成功");
            } else {
                cocoMessage.error(2000,"删除用户失败");
            }
        }
    });
}


function deleteCourseStudent(formData){
    $.ajax({
        url: '/deleteCourseStudent/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                cocoMessage.success(2000,res.data);
            } else {
                cocoMessage.error(2000,"删除用户失败");
            }
        }
    });
}

/**
 * 修改用户密码
 * */

$('#revise-password').click(function () {
    showReviseModel();
})


/**
 * 当鼠标移入讨论框，删除键显现
 * */
$(document).on('mouseenter', '.chat-item', function () {
    $(this).find('.chat-del').css('visibility', 'visible');
});
/**
 * 当鼠标从讨论框移走，删除键消失
 * */
$(document).on('mouseleave', '.chat-item', function () {
    $(this).find('.chat-del').css('visibility', 'hidden');
});

/**
 * 查询讨论目的室
 * */
function selectChatRoom(selectDom) {
    // 记录当前选中的聊天室，用于后续更新消息数量
    selectedChatRoomDom = selectDom;
    // 显示右边聊天框
    $('.right-panel').css('visibility', 'visible');
    $('.add-panel').css('visibility','visible');
    $('.chat-selected').removeClass('chat-selected');
    // 添加点击被选中状态
    $(selectDom).addClass('chat-selected');
    // 获取当前聊天室标题
    let chatTitle = $(selectDom).find('.chat-title').text();
    // TODO 选择聊天室
    $('.right-title').text(chatTitle);
    $('.right-chatRoom').empty();
    //将讨论室成员列表清空
    $('.user-box').empty();
    //将讨论的基本信息清空
    $('.add-text-content').val("");
    $('.add-text-key').val("");
    $('.add-text-item').val("");
    // 切换聊天室将页码置为1
    msgPageIndex = 1;
    let formData = new FormData();
    formData.append("pageIndex", msgPageIndex);
    formData.append("roomName", chatTitle);
    let fomDataChatRoom=new FormData();
    fomDataChatRoom.append("chatName",chatTitle);
    //可视化讨论室的基本信息
    queryChatRoomByName(fomDataChatRoom);
    //可视化讨论室的成员信息
    queryChatRoomUser(fomDataChatRoom);
    loadingMsg(formData, $(selectDom).find('.chat-num')[0]);
    msgPageIndex++;
    // 添加后滚动条长度
    let afterScrollLength = $('.right-chatRoom').prop('scrollHeight');
    // 将滚动条滚动到没添加前的位置
    $('.right-chatRoom').scrollTop(afterScrollLength)
    connect(chatTitle);
}

$(document).on('click', '.chat-item-main', function () {
    selectChatRoom(this)
});

/**
 * 当鼠标点击讨论室框 选择该讨论室
 * */
$(document).on('click', '.chat-item',function () {
    //WenXinTest();
    selectChatRoom(this)
});

/**
 * 删除讨论室
 * */
function delChatRoom(isCreate, dom) {
    if (isCreate) {
        if (confirm("创建者删除将会清空聊天记录！")){
            dom.detach();
        }else {

        }
    }else {
        let roomName = $(dom).find('.chat-title').text();
        let formData = new FormData();
        formData.append("roomName", roomName);
        $.ajax({
            url: '/delChat/',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    cocoMessage.success(2000, res.data)
                    dom.detach();
                }else if(res.code === 201) {
                    cocoMessage.info(2000, res.data)
                }else {
                    // 重定向到登录页
                    window.location.href = '/loginPage';
                }
            },
            error:function (res) {
                // 重定向到登录页
                window.location.href = '/loginPage';
            }
        })

    }
}

/**
 * 删除讨论室
 * */
$(document).on('click', '.chat-del', function (event) {
    event.stopPropagation()
    // TODO 请求后端删除
    let delDom = $(this).parent('.chat-item')
    delChatRoom(false, delDom);
});

/**
 * 隐藏选项模态框
 * */
function hiddenModel() {
    $('.overlay').css('z-index', '');
    $('.model').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

function hiddenReviseModel() {
    $('.overlay').css('z-index', '');
    $('.revise-model').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

function hiddenInsertModel() {
    $('.overlay').css('z-index', '');
    $('.insert-model').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

function hiddenInsertCourseModel() {
    $('.overlay').css('z-index', '');
    $('.insert-course-model').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

function hiddenInsertCourseStudentModel() {
    $('.overlay').css('z-index', '');
    $('.insert-course-student-model').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

function hiddenMyModel() {
    $('.overlay').css('z-index', '');
    $('.myModel').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

/**
 * 显示模态框
 * */
function showModel() {
    $('.overlay').css('z-index', '1');
    $('.model').css('visibility', 'visible');
}

function showReviseModel() {
    $('.overlay').css('z-index', '1');
    $('.revise-model').css('visibility', 'visible');
}

function showMyModel(formData) {
    $('.overlay').css('z-index', '1');
    $('.myModel').css('visibility', 'visible');

}

function showInsertModel() {
    $('.overlay').css('z-index', '1');
    $('.insert-model').css('visibility', 'visible');
}

function showInsertCourseModel() {
    console.info("显示了新增课程");
    $('.overlay').css('z-index', '1');
    $('.insert-course-model').css('visibility', 'visible');
}

function showInsertCourseStudentModel() {
    console.info("显示了新增课程-学生");
    $('.overlay').css('z-index', '1');
    $('.insert-course-student-model').css('visibility', 'visible');
}

/**
 * 加入讨论
 * */
function joinChat() {
    let chatRoom = $('#input-room-name').val();
    let formData = new FormData();
    let course= $('#input-course-name').val();
    let teacher=$('#input-teacher-name').val();
    formData.append("chatRoom",chatRoom);
    formData.append("course",course);
    formData.append("teacher",teacher);
    if (chatRoom !== '') {
        if(course === '' || teacher === ''){
            cocoMessage.error("请填写讨论室的完整信息");
        }else{
            $.ajax({
                url: '/checkCourseStudent/',
                type: 'post',
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    if (res.code === 200) {
                        let roomId = res.data.roomId;
                        let formData = new FormData();
                        formData.append("roomId",roomId);
                        insertNewUserRoom(formData);
                        cocoMessage.success(2000,"加入讨论室成功！")
                        $('.item-box').append(`<div class="chat-item">
                                <div class="chat-del"></div>
                                <div class="chat-title">${chatRoom}</div>
                                <div class="chat-bottom">
                                    <div class="chat-time">${getDateTime(19)}</div>
                                    <div class="chat-num">0 条对话</div>
                                </div>
                            </div>`);
                        //制空输入框
                        $('#input-room-name').val("");
                        $('#input-course-name').val("");
                        $('#input-teacher-name').val("");
                        hiddenModel();
                    }else if(res.code === 201){
                        //该讨论室不存在，则直接跳转创建
                        cocoMessage.info(2000, res.data)
                        hiddenModel();
                        showMyModel(formData);
                    }
                },
                error: function (res) {
                    // 重定向到登录页
                    cocoMessage.info(2000,"加入讨论室错误");
                },
            })
        }
    }else {
        cocoMessage.warning(2000, "讨论室不能为空！！")
    }
}

/**
 * 新增讨论
 * */
function addChat() {
    let chatRoom = $('#input-room-name').val();
    let formData = new FormData();
    let course= $('#input-course-name').val();
    let teacher=$('#input-teacher-name').val();

    let item=$('#input-room-item').val();
    let content=$('#input-room-content').val();
    let key=$('#input-room-content-key').val();
    formData.append('course', course);
    formData.append('teacher',teacher);
    formData.append('roomName', chatRoom);

    formData.append('item',item);
    formData.append('content',content);
    formData.append('key',key);
    if (chatRoom !== '') {
        if(item === '' || content === '' || key===''){
            cocoMessage.error("请填写讨论室的完整信息");
        }else{
            $.ajax({
                url: '/addChat/',
                type: 'post',
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    if (res.code === 200) {
                        cocoMessage.success(2000, res.data)
                        $('.item-box').append(`<div class="chat-item">
                                <div class="chat-del"></div>
                                <div class="chat-title">${chatRoom}</div>
                                <div class="chat-bottom">
                                    <div class="chat-time">${getDateTime(19)}</div>
                                    <div class="chat-num">0 条对话</div>
                                </div>
                            </div>`);
                        //制空输入框
                        $('.model-input').val("");
                        $('textarea[name="item"]').val("");
                        $('textarea[name="content"]').val("");
                        $('textarea[name="key"]').val("");
                    }else if(res.code === 201) {
                        cocoMessage.info(2000, res.data)
                    }else {
                        // 重定向到登录页
                        window.location.href = '/loginPage';
                    }
                },
                error: function (res) {
                    // 重定向到登录页
                    window.location.href = '/loginPage';
                },
            })
        }

    }else {
        cocoMessage.warning(2000, "讨论室不能为空！！")
    }
}

/**
 * 点击页面其他面板，新增模板消失
 * */
$('.overlay').click(function () {
    hiddenModel();
    hiddenMyModel();
    hiddenReviseModel();
    hiddenInsertModel();
    hiddenInsertCourseModel();
    hiddenInsertCourseStudentModel();
});

/**
 * 添加新讨论组，显示模板
 * */
$(".new-chat").click(function () {
    showModel()
});

/**
 * 讨论分析
 * */
$(".thy").click(function (){
    //主题检测
    let roomName = $('.right-title').text();
    //let roomName = encodeURIComponent(chatTitle);
    console.log("roomName+",roomName);
    window.location.href = '/analysis/?roomName=' + roomName;
});

/**
 * 加入新的讨论室
 * */
$('.add').click(function () {
   joinChat();
});


/**
 * 创建新的讨论室
 * */
$('.create').click(function () {
    // TODO 请求成功隐藏模态框，并添加聊天室
    let chatRoom = $('#input-room-name').val();
    let formData = new FormData();
    let course= $('#input-course-name').val();
    let teacher=$('#input-teacher-name').val();
    hiddenModel();
    showMyModel(formData);
});

$('.sure').click(function () {
    // TODO 请求成功隐藏模态框，并添加聊天室
    hiddenMyModel();
    addChat();
});

$('.cancel').click(function () {
    // TODO 请求成功隐藏模态框，并添加聊天室
    hiddenMyModel();
});

$('.revise-cancel').click(function () {
    // TODO 请求成功隐藏模态框
    hiddenReviseModel();
});


$('.insert-sure').click(function () {
    // TODO 请求成功隐藏模态框
    insertNewUser();
});

$('.insert-course-sure').click(function () {
    // TODO 请求成功隐藏模态框
    insertNewCourse();
});

$('.insert-cancel').click(function () {
    // TODO 请求成功隐藏模态框
    hiddenInsertModel();
});

$('.insert-course-cancel').click(function () {
    // TODO 请求成功隐藏模态框
    hiddenInsertCourseModel();
});

$('.insert-course-student-sure').click(function () {
    // TODO 请求成功隐藏模态框
    insertNewCourseStudent();
});

$('.insert-course-student-cancel').click(function () {
    // TODO 请求成功隐藏模态框
    hiddenInsertCourseStudentModel();
});



$('.revise-sure').click(function () {
    // TODO 请求成功隐藏模态框，并添加聊天室
    let password = $('#revise-input').val();
    let newPassage_again = $('#revise-input-again').val();
    console.log(password);
    console.log(newPassage_again);
    let regex=/^[a-zA-Z0-9]{8,}$/;
    if(regex.test(password)){
        //如果两次密码相同，则可以修改
        if(password === newPassage_again){
            hiddenReviseModel();
            RevisePassword(password);
            $('#revise-input').val("");
            $('#revise-input-again ').val("");
        }else{
            alert("请输入相同的新密码！")
            $('#revise-input-again ').val("");
        }

    }else{
        alert("请输入8位以上包含大小写字母或数字的密码！");
    }
});



/**
 * 可拓展文本框设置高度
 * */
var textarea = $('#resizable-textarea');


/**
 * 自动扩展输入框的高度
 * */
textarea.on('input', function() {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight) + 'px';
});

$('.query-user-clean').click(function (){
    $('#query-user-result').css('visibility','hidden');
});

$('.query-course-clean').click(function (){
    $('#query-course-result').css('visibility','hidden');
});

$('.query-course-student-clean').click(function (){
    $('#query-course-student-result').css('visibility','hidden');
});
/**
 * 查询用户信息
 * */
$('.query-user').click(function (){
    console.log("点击了查询按钮")
    let name = "";
    if($('#query-name').val() !== null){
        name = $('#query-name').val();
    }
    console.info(name);
    let code = "";
    if($('#query-code').val() !== null){
        code = $('#query-code').val();
    }
    console.info(code);
    //初始密码
    console.log(name,code);
    let formData = new FormData();
    formData.append("name",name);
    formData.append("code",code);
    $.ajax({
        url: '/queryUser/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                let user = res.data;
                if(user !== null){
                    let name = user.name;
                    let code = user.code;
                    let role = user.role;
                    console.log(name,code,role);
                    if(role === 0){
                         role="管理员";
                    }else if(role === 1){
                         role="教师";
                    }else if(role === 2){
                         role="学生";
                    }else{
                         role="未知";
                    }
                    $('#query-user-result').css('visibility','visible');
                    $('#query-user-result-table').find('td').eq(0).text(name);
                    $('#query-user-result-table').find('td').eq(1).text(code);
                    $('#query-user-result-table').find('td').eq(2).text(role);
                }
            }else{
                cocoMessage.error('2000', res.msg);
            }
        },
        error: function (res) {
            // 重定向到登录页
            alert("添加用户错误");
        },
    })
})

/**
 * 查询课程信息
 * */
$('.query-course').click(function (){
    console.log("点击了查询课程按钮")
    if($('#query-course-name').val() === null || $('#query-course-teacher').val() === null){
        cocoMessage.error("请填写完整查询的课程信息！");
    }else{
        let name = $('#query-course-name').val();
        let teacher = $('#query-course-teacher').val();
        console.info(teacher);
        //初始密码
        console.log(name,teacher);
        let formData = new FormData();
        formData.append("name",name);
        formData.append("teacher",teacher);
        $.ajax({
            url: '/queryCourse/',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    let course = res.data;
                    if(course !== null){
                        $('#query-course-result').css('visibility','visible');
                        $('#query-course-result-table').find('td').eq(0).text(course.id);
                        $('#query-course-result-table').find('td').eq(1).text(course.name);
                        $('#query-course-result-table').find('td').eq(2).text(course.teacher);
                        $('#query-course-result-table').find('td').eq(3).text(course.teacherCode);
                    }
                }else{
                    cocoMessage.error('2000', res.msg);
                }
            },
            error: function (res) {
                // 重定向到登录页
                alert("查询课程错误");
            },
        })
    }
})


/**
 * 查询课程-学生信息
 * */
$('.query-course-student').click(function (){
    console.log("点击了查询学生-课程按钮")
    if($('#query-course-student-code').val() === null || $('#query-course-course-code').val() === null){
        cocoMessage.error("请填写完整查询的学生-课程信息！");
    }else{
        let studentCode = $('#query-course-student-code').val();
        let courseCode = $('#query-course-course-code').val();
        console.log(studentCode,courseCode);
        let formData = new FormData();
        formData.append("studentCode",studentCode);
        formData.append("courseCode",courseCode);
        console.log(formData.get("studentCode"),formData.get("courseCode"));
        $.ajax({
            url: '/queryCourseStudent/',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    let courseStudent = res.data;
                    console.info(courseStudent.courseCode);
                    if(courseStudent !== null){
                        $('#query-course-student-result').css('visibility','visible');
                        $('#query-course-student-result-table').find('td').eq(0).text(courseStudent.studentCode);
                        $('#query-course-student-result-table').find('td').eq(1).text(courseStudent.student);
                        $('#query-course-student-result-table').find('td').eq(2).text(courseStudent.courseName);
                        $('#query-course-student-result-table').find('td').eq(3).text(courseStudent.teacher);
                    }
                }else{
                    cocoMessage.error('2000', res.msg);
                }
            },
            error: function (res) {
                // 重定向到登录页
                alert("查询学生-课程错误");
            },
        })
    }
})

/**
 * 添加新用户
 * */
function insertNewUser() {
    let name = $('#insert-name').val();
    let code =  $('#insert-code').val();
    //初始密码
    let role =  $('#insert-role').val();
    console.log(name,code,role);
    let formData = new FormData();
    formData.append("name",name);
    formData.append("code",code);
    formData.append("role",role);
    if(!isRightRole(role)){
        cocoMessage.success(2000,"请输入正确的角色!")
        $('#insert-role').val("");
    }else{
        $.ajax({
            url: '/register',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    console.log(res.data)
                    cocoMessage.success(2000,"添加用户成功")
                    hiddenInsertModel();
                }else{
                    cocoMessage.error('2000', res.msg);
                }
            },
            error: function (res) {
                // 重定向到登录页
                alert("添加用户错误");
            },
        })
    }
}

/**
 * 检测角色
 * */
function isRightRole(role) {
    const num = Number(role);
    return [0, 1, 2, 3].includes(num);
}
/**
 * 添加课程
 * */
function insertNewCourse() {
    let name = $('#insert-course-name').val();
    let code =  $('#insert-course-code').val();
    let teacher =  $('#insert-course-teacher').val();
    console.log(name,code,teacher);
    let formData = new FormData();
    formData.append("name",name);
    formData.append("code",code);
    formData.append("teacher",teacher);
    if(name === '' || code === '' || teacher === ''){
        cocoMessage.error(2000,"请输入课程的完整信息!");
    }else{
        $.ajax({
            url: '/courseInsert/',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    cocoMessage.success(2000, res.data)
                    console.log(res.data)
                    cocoMessage.success(2000,"添加课程成功！");
                    hiddenInsertCourseModel();
                }else{
                    cocoMessage.error('2000', res.msg);
                }
            },
            error: function (res) {
                // 重定向到登录页
                alert("添加用户错误");
            },
        })
    }
}

/**
 * 添加课程-学生关系
 * */
function insertNewCourseStudent() {
    let studentCode = $('#insert-course-student-code').val();
    let course =  $('#insert-course-course-name').val();
    let teacher =  $('#insert-course-course-teacher').val();
    console.log(studentCode,course,teacher);
    let formData = new FormData();
    formData.append("studentCode",studentCode);
    formData.append("course",course);
    formData.append("teacher",teacher);
    if(studentCode === '' || course === '' || teacher === ''){
        cocoMessage.error(2000,"请输入学生-课程的完整信息!");
    }else{
        $.ajax({
            url: '/InsertCourseStudent/',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    console.log(res.data)
                    cocoMessage.success(2000,"添加课程成功！");
                    hiddenInsertCourseStudentModel();
                }else{
                    cocoMessage.error('2000', res.msg);
                }
            },
            error: function (res) {
                // 重定向到登录页
                alert("添加学生-课程错误");
            },
        })
    }
}


/**
 * 添加课程-学生关系
 * */
function insertNewUserRoom(formData) {
    $.ajax({
        url: '/InsertUserRoom/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                console.log(res.data)
            }else{
                cocoMessage.error('2000', res.msg);
            }
        },
        error: function (res) {
            // 重定向到登录页
            alert("添加学生-课程错误");
        },
    })
}


/**
 * 生成报告
 * */
function createPDF() {
    let chatTitle=$('.right-title').text();
    console.log("chatTitle是"+chatTitle);
    let formData = new FormData();
    formData.append("chatRoomName",chatTitle);

    let newWindow = window.open('', '_blank');
    $.ajax({
        url: '/pdf/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res !== null) {
                cocoMessage.success(2000, res.data)
                let pdfModel = res;
                console.log(res)
                //alert("返回的html路径：" + pdfModel);
                //window.open(htmlPath,'_blank')
                if (newWindow && !newWindow.closed) {
                    newWindow.document.write(res);
                    newWindow.document.close(); // 关闭文档流，允许页面渲染
                } else {
                    // 如果新窗口被关闭或无法写入，可以给出提示或处理错误
                    console.error('新窗口已关闭或无法写入内容');
                }
            }else {
                // 重定向到登录页
                window.location.href = '/loginPage';
            }
        },
        error: function (res) {
            // 重定向到登录页
            window.location.href = '/loginPage';
        },
    })
}

/**
 * 生成报告
 * */
function createHtml() {
    let chatTitle=$('.right-title').text();
    console.log("chatTitle是"+chatTitle);
    let formData = new FormData();
    formData.append("chatRoomName",chatTitle);
    let newWindow = window.open('', '_blank');
    $.ajax({
        url: '/craeteHtml/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res !== null) {
                cocoMessage.success(2000, res.data)
                let pdfModel = res;
                console.log(res)
                //alert("返回的html路径：" + pdfModel);
                //window.open(htmlPath,'_blank')
                if (newWindow && !newWindow.closed) {
                    newWindow.document.write(res);
                    newWindow.document.close(); // 关闭文档流，允许页面渲染
                } else {
                    // 如果新窗口被关闭或无法写入，可以给出提示或处理错误
                    console.error('新窗口已关闭或无法写入内容');
                }
            }else {
                // 重定向到登录页
                window.location.href = '/loginPage';
            }
        },
        error: function (res) {
            // 重定向到登录页
            window.location.href = '/loginPage';
        },
    })
}

/**
 * 发送属性控制
 * */
$('#text-message').on('change', function () {
    if ($('#text-message').prop('checked')) {
        // 更改发送按钮属性
        $('.send-img').removeClass('file');
        $('.send-img').addClass('text');
        // 更改发送框
        fileInput = $('.file-input').detach();
        $('.message-input').prepend(textInput)
    }
});

$('#file-message').on('change', function () {
    if ($('#file-message').prop('checked')) {
        // 更改发送按钮属性
        $('.send-img').removeClass('text');
        $('.send-img').addClass('file');
        // 更改发送框
        textInput = $('.text-input').detach();
        $('.message-input').prepend(fileInput)
    }
});

/**
 * 拖拽文件进入输入框自动改变文本输入样式
 * */
$('.right-panel').on("dragenter", function (event) {
    $('.left-overlay').css('display', 'block');
    // 判断radio是否处于选中状态
    if ($('#text-message').prop('checked')) {
        $('#text-message').prop('checked', false);
        //$('#question-message').prop('checked', false);
        $('#file-message').prop('checked', true);
        // // 更改发送按钮属性
        $('.send-img').removeClass('text');
        $('.send-img').addClass('file');
        // 更改发送框
        textInput = $('.text-input').detach();
        $('.message-input').prepend(fileInput)
    }

});

/**
 * 组织浏览器的默认行为，允许浏览器的元素上叠加文件
 * */
$('.right-panel').on("dragover", function (event) {
    event.preventDefault();
});

/**
 * 定义脱离行为
 * */
$('.right-panel').on("dragleave", function (event) {
    if (!$(event.relatedTarget).closest('.right-panel').length) {
        $('.left-overlay').css('display', 'none');
    }
});


$('.right-panel').on("drop", function (event) {
    event.preventDefault();
    const files = Array.from(event.originalEvent.dataTransfer.files);
    // 定义一个数组来存储不重复的文件
    const uniqueFiles = [];
    // 遍历文件列表，将不重复的文件添加到 uniqueFiles 中
    files.forEach(file => {
        if (!uniqueFiles.find(f => f.name === file.name && f.size === file.size)) {
            uniqueFiles.push(file);
        }
    });
    const finalFiles = []
    // 遍历不重复文件数组，将已经添加过的文件从中去除，同时只添加小于60M的文件
    uniqueFiles.forEach(file => {
        if (file.size >= maxFileSize) {
            cocoMessage.error(2000, `文件：${file.name} 太大了`)
        }else if (!fileArray.find(f => f.name === file.name && f.size === file.size)) {
            finalFiles.push(file);
        }
    });

    if (finalFiles && finalFiles.length > 0) {
        $('.file-input').addClass("hide-file-input-before");
        finalFiles.forEach(file => {
            // 将文件添加到全局数组中
            fileArray.push(file)
            const reader = new FileReader();
            reader.onload = function (event) {
                // 处理图片类文件
                if (file.type.indexOf("image") === 0) {
                    $('.file-input').append(`<div class="file-item">
                                                    <div class="file-del"></div>
                                                    <img src="${event.target.result}" alt="${file.name}" class="file-preview" draggable="false">
                                                    <span class="file-name" title="${file.name}">${file.name}</span>
                                                </div>`);
                } else {
                    $('.file-input').append(`<div class="file-item">
                                                    <div class="file-del"></div>
                                                    <img src="../../static/img/unknown.png" alt="${file.name}" class="file-preview" draggable="false">
                                                    <span class="file-name" title="${file.name}">${file.name}</span>
                                                </div>`)
                }
            };
            reader.readAsDataURL(file);
        });
        $('.file-input').focus();

    }
    $('.left-overlay').css('display', 'none');
});

/**
 *
 * 删除文件，取消发送
 * */
$(document).on('click', '.file-del', function () {
    $(this).parent('.file-item').detach();
    let fileName = $(this).siblings('.file-name').text();
    fileArray = fileArray.filter(file => file.name !== fileName);
    if (fileArray.length === 0) {
        $('.file-input').removeClass("hide-file-input-before");
    }
});

$(document).on('mousewheel', '.file-input', function(e) {
    // 设置鼠标移动的距离
    let moveX = e.originalEvent.deltaY;
    // 控制容器横向滚动
    $(this).scrollLeft($(this).scrollLeft() + moveX);
});

/**
 *
 *修改输入行数
 */
function changeTextareaHeight(dom) {
    let textarea = document.querySelector(dom)
    let _scrollHeight = textarea.scrollHeight;
    if (dom === '.text-input') {
        // 最大显示五行
        if (_scrollHeight / 21 <= 5){
            textarea.style.height = `${_scrollHeight}px`;
        }else {
            textarea.style.height = `105px`;
        }
    }
}

$('.text-input').on('input', function () {
    changeTextareaHeight('.text-input')
});

/**
 * 获取文件的大小
 * */
function getConvertSize(fileSize) {
    let convertSize = '';
    let M = 1048576;
    let K = 1024;
    if (fileSize < M) {
        convertSize = `${(fileSize / K).toFixed(2)} KB`;
    } else {
        convertSize = `${(fileSize / M).toFixed(2)} MB`
    }
    return convertSize
}

/**
 * 将 msg 中的连接转为可以点击的连接
 * @Author: Junior
 * @Date: 2023/10/20
 * @param msg
 */
function getConvertMsg(msg) {
    let urlRegex = /(http:\/\/|https:\/\/|www\.)([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/gi;

    // 先将 msg 中html标签全部转换为实体
    msg = msg.replace(/</g, '&lt;')
             .replace(/>/g, '&gt;')


    // 将消息中http连接转换为 <a> 标签
    return msg.replace(urlRegex, function (url) {
        let httpRegex = /^(http:\/\/|https:\/\/)/;
        let wholeUrl = "";
        if (!httpRegex.test(url)) {
            // 如果不是以http://或https://开头，则在最前面添加http://
            wholeUrl = 'http://' + url;
        } else {
            wholeUrl = url;
        }
        return '<a href="' + wholeUrl + '" target="_blank">' + url + '</a>';
    });
}

/**
 *
 * 加载信息消息
 * */
function insertText(horizontal, vertical, user, code, sendMsg) {
    let convertMsg = getConvertMsg(sendMsg);
    let $rightChatRoom = $('.right-chatRoom')
    if (horizontal === 'left') {
        if (vertical === 'head') {
            // 往前添加靠左的气泡
            $rightChatRoom.prepend(`<div class="bubble">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().first()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        } else if (vertical === 'end'){
            // 往后添加靠左的气泡
            $rightChatRoom.append(`<div class="bubble">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().last()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        }
    }else if (horizontal === 'right') {
        if (vertical === 'head') {
            // 往前添加靠右的气泡
            $rightChatRoom.prepend(`<div class="bubble">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-right">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().first()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        } else if (vertical === 'end'){
            // 往后添加靠右的气泡
            $rightChatRoom.append(`<div class="bubble">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-right">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`)
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().last()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        }
    }
    return $rightChatRoom.children().last();
}

/**
 * 加载问题消息
 * */
function insertQuestion(horizontal, vertical, user, code, sendMsg) {
    let convertMsg = getConvertMsg(sendMsg);
    let $rightChatRoom = $('.right-chatRoom')
    if (horizontal === 'left') {
        if (vertical === 'head') {
            // 往前添加靠左的气泡
            $rightChatRoom.prepend(`<div class="bubble">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info-question">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().first()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        } else if (vertical === 'end'){
            // 往后添加靠左的气泡
            $rightChatRoom.append(`<div class="bubble">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info-question">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().last()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        }
    }else if (horizontal === 'right') {
        if (vertical === 'head') {
            // 往前添加靠右的气泡
            $rightChatRoom.prepend(`<div class="bubble">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-question">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().first()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        } else if (vertical === 'end'){
            // 往后添加靠右的气泡
            $rightChatRoom.append(`<div class="bubble">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-question">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`)
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().last()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        }
    }
    return $rightChatRoom.children().last();
}

/**
 * 加载回答消息
 * */
function insertAnswer(horizontal, vertical, user, code, sendMsg) {
    let convertMsg = getConvertMsg(sendMsg);
    let $rightChatRoom = $('.right-chatRoom')
    if (horizontal === 'left') {
        if (vertical === 'head') {
            // 往前添加靠左的气泡
            $rightChatRoom.prepend(`<div class="bubble">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info-answer">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().first()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        } else if (vertical === 'end'){
            // 往后添加靠左的气泡
            $rightChatRoom.append(`<div class="bubble">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info-answer">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().last()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        }
    }else if (horizontal === 'right') {
        if (vertical === 'head') {
            // 往前添加靠右的气泡
            $rightChatRoom.prepend(`<div class="bubble">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-answer">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`);
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().first()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        } else if (vertical === 'end'){
            // 往后添加靠右的气泡
            $rightChatRoom.append(`<div class="bubble">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-answer">
                                                <span class="bubble-text"></span>
                                            </div>
                                        </div>
                                    </div>`)
            // 获取最后添加的气泡
            let lastBubble = $($rightChatRoom.children().last()).find('.bubble-text')[0];
            lastBubble.innerHTML = convertMsg
        }
    }
    return $rightChatRoom.children().last();
}

/**
 * 加载图片消息
 * */
function insertImage(horizontal, vertical, user, code, sendMsg, file) {
    let $rightChatRoom = $('.right-chatRoom')
    if (horizontal === 'left') {
        if (vertical === 'head') {
            // 往前添加靠左的气泡
            $rightChatRoom.prepend(`<div class="bubble" name="${file.name}">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info-file">
                                                <img class="bubble-image" src="${sendMsg}" draggable="false" alt="">
                                            </div>
                                        </div>
                                    </div>`);
        }else if (vertical === 'end') {
            // 往后添加靠左的气泡
            $rightChatRoom.append(`<div class="bubble" name="${file.name}">
                                <div class="bubble-user-box">
                                    <span class="bubble-user">${user}</span>
                                    <span class="append-info">${code}</span>
                                </div>
                                <div class="bubble-info-box">
                                    <div class="bubble-info-file">
                                        <img class="bubble-image" src="${sendMsg}" draggable="false" alt="">
                                    </div>
                                </div>
                            </div>`);
        }
    }else if (horizontal === 'right') {
        if (vertical === 'head') {
            // 往前添加靠右的气泡
            $rightChatRoom.prepend(`<div class="bubble" name="${file.name}">
                                        <div class="bubble-user-box-right">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box-right">
                                            <div class="bubble-info-right-file">
                                                <img class="bubble-image" src="${sendMsg}" draggable="false" alt="">
                                            </div>
                                        </div>
                                    </div>`);
        }else if (vertical === 'end') {
            // 往后添加靠右的气泡
            $rightChatRoom.append(`<div class="bubble" name="${file.name}">
                                    <div class="bubble-user-box-right">
                                        <span class="bubble-user">${user}</span>
                                        <span class="append-info">${code}</span>
                                    </div>
                                    <div class="bubble-info-box-right">
                                        <div class="bubble-info-right-file">
                                            <img class="bubble-image" src="${sendMsg}" draggable="false" alt="">
                                        </div>
                                    </div>
                                </div>`)
        }
    }
    return $rightChatRoom.children().last();
}

/**
 * 加载文件等其他气泡
 * */
function insertOthers(horizontal, vertical, user, code, sendMsg, file) {
    let fileSize = file.size;
    let convertSize = getConvertSize(file.size);
    let $rightChatRoom = $('.right-chatRoom');
    if (horizontal === 'left') {
        if (vertical === 'head') {
            // 往前添加靠左的气泡
            $rightChatRoom.prepend(`<div class="bubble" name="${file.name}">
                                        <div class="bubble-user-box">
                                            <span class="bubble-user">${user}</span>
                                            <span class="append-info">${code}</span>
                                        </div>
                                        <div class="bubble-info-box">
                                            <div class="bubble-info-file">
                                                <div class="bubble-file" name="${sendMsg}">
                                                    <div class="bubble-file-info">
                                                        <div class="bubble-file-name" title="${file.name}">${file.name}</div>
                                                        <div class="bubble-file-size">${convertSize}</div>
                                                    </div>
                                                    <img class="bubble-file-img" src="../../static/img/unknown.png" alt="" draggable="false">
                                                </div>
                                            </div>
                                        </div>
                                    </div>`);
        }else if (vertical === 'end') {
            // 往后添加靠右的气泡
            $rightChatRoom.append(`<div class="bubble" name="${file.name}">
                                    <div class="bubble-user-box">
                                        <span class="bubble-user">${user}</span>
                                        <span class="append-info">${code}</span>
                                    </div>
                                    <div class="bubble-info-box">
                                        <div class="bubble-info-file">
                                            <div class="bubble-file" name="${sendMsg}">
                                                <div class="bubble-file-info">
                                                    <div class="bubble-file-name" title="${file.name}">${file.name}</div>
                                                    <div class="bubble-file-size">${convertSize}</div>
                                                </div>
                                                <img class="bubble-file-img" src="../../static/img/unknown.png" alt="" draggable="false">
                                            </div>
                                        </div>
                                    </div>
                                </div>`)
        }

    } else if (horizontal === 'right') {
        if (vertical === 'head') {
            // 往前添加靠右的气泡
            $rightChatRoom.prepend(`<div class="bubble" name="${file.name}">
                                    <div class="bubble-user-box-right">
                                        <span class="bubble-user">${user}</span>
                                        <span class="append-info">${code}</span>
                                    </div>
                                    <div class="bubble-info-box-right">
                                        <div class="bubble-info-right-file">
                                            <div class="bubble-file" name="${sendMsg}">
                                                <div class="bubble-file-info">
                                                    <div class="bubble-file-name" title="${file.name}">${file.name}</div>
                                                    <div class="bubble-file-size">${convertSize}</div>
                                                </div>
                                                <img class="bubble-file-img" src="../../static/img/unknown.png" alt="" draggable="false">
                                            </div>
                                        </div>
                                    </div>
                                </div>`)

        }else if (vertical === 'end') {
            // 往后添加靠右的气泡
            $rightChatRoom.append(`<div class="bubble" name="${file.name}">
                                    <div class="bubble-user-box-right">
                                        <span class="bubble-user">${user}</span>
                                        <span class="append-info">${code}</span>
                                    </div>
                                    <div class="bubble-info-box-right">
                                        <div class="bubble-info-right-file">
                                            <div class="bubble-file" name="${sendMsg}">
                                                <div class="bubble-file-info">
                                                    <div class="bubble-file-name" title="${file.name}">${file.name}</div>
                                                    <div class="bubble-file-size">${convertSize}</div>
                                                </div>
                                                <img class="bubble-file-img" src="../../static/img/unknown.png" alt="" draggable="false">
                                            </div>
                                        </div>
                                    </div>
                                </div>`)
        }
    }
    return $rightChatRoom.children().last();
}

/**
 * 气泡类型分拣
 * */
function drawBubble(horizontal, vertical, user, code, sendMsg, sendType, file) {
    let thisBubble;
    if (sendType === 'text') {
        thisBubble = insertText(horizontal, vertical, user, code, sendMsg);
    }else if (sendType === 'image') {
        thisBubble = insertImage(horizontal, vertical, user, code, sendMsg, file);
    }else if(sendType === 'question'){
        thisBubble = insertQuestion(horizontal,vertical,user,code,sendMsg);
    }else if(sendType === 'answer'){
        thisBubble = insertAnswer(horizontal,vertical,user,code,sendMsg);
    }else if (sendType === 'others') {
        thisBubble = insertOthers(horizontal, vertical, user, code, sendMsg, file)
    }
    return thisBubble;
}

/**
 * 放大显示
 * */
$(document).on('click', '.bubble-image', function () {
    // 显示大图
    let imgSrc = $(this).attr('src')
    $('.show-img').attr('src', imgSrc)
    $('.overlay').css('z-index', '1');
    $('.show-img').css('visibility', 'visible');
});

/**
 * 正在发送
 * */
function isSending(dom) {
    // 移除发送失败标志
    $(dom).find('.bubble-error').remove();
    // 添加正在发送标志
    if ($(dom).find('.bubble-loading').length === 0)
        $(dom).find('.bubble-info-box-right').prepend(`<img src="../../static/img/loading.png" class="bubble-loading">`)
}

/**
 * 发送成功
 * */
function sendSuccess(dom) {
    // 移除正在发送标志
    $(dom).find('.bubble-loading').remove();
}
/**
 * 发送失败
 * */
function sendError(dom) {
    // 移除正在发送标志
    $(dom).find('.bubble-loading').remove();
    // 添加发送失败标志
    if($(dom).find('.bubble-error').length === 0)
        $(dom).find('.bubble-info-box-right').prepend(`<img src="../../static/img/error.png" class="bubble-error">`)
}

/**
 * 点击 失败气泡
 * */
$(document).on('click', '.bubble-error', function () {
    let bubbleDom = $(this).parents('.bubble')
    let bubbles = [bubbleDom[0]]
    let formData = new FormData();
    // 发送失败消息重新发送
    if (bubbleDom.find('.bubble-info-right-file').length > 0) {
        // 重发文件
        let fileName = bubbleDom.attr('name');
        let file = sendFileArray.find(f => f.name === fileName);
        // 更改为发送状态
        isSending(bubbleDom);
        // 使用ajax发送文件
        formData.append('index', 0);
        formData.append('file', file);
        formData.append('roomName', $('.right-title').text());
        ajaxFile(formData, bubbles);


    }else if (bubbleDom.find('.bubble-info-right').length > 0) {
        // 重发文字
        let sendMessage = bubbleDom.find('.bubble-text').text();
        // 去除发送失败标志
        $(bubbleDom[0]).find('.bubble-error').remove();
        websocketSend(sendMessage,bubbleDom[0])
    }
});


/**
 * webcoket发送信息
 * */
function websocketSend(sendMessage, bubble) {
    if (ws.readyState === 1) {
        ws.send(sendMessage);
        msgCount += 1;
        $(selectedChatRoomDom).find('.chat-num').text(`${msgCount} 条对话`);
    } else {
        sendError(bubble)
    }
}
/**
 * 发送信息第二次分拣  先进行主题检测，然后进行问题检测，智能问答
 * */

function isQuestion(sendMessage,roomName) {
    let searchTerm = "@文文";
    if (sendMessage.includes(searchTerm)) {
        console.log("包含@文文是问题")
        //直接调用文心一言
        WenXinModal(sendMessage,roomName);
    }
}
/**
 * 发送普通信息
 * */
function sendMsg(sendMessage) {
    console.info("开始发送信息")
    let user = $(".user-name").contents().filter(function () {
                    return this.nodeType === 3; // 筛选文本节点
                }).text().trim();
    let code = $(".user-name").contents().filter(function () {
                    return this.nodeType === 1; // 筛选element节点
                }).text().trim();
    let sendType = 'text';
    let file = '';
    let thisBubble = drawBubble('right', 'end', user, code,  sendMessage, sendType, file)
    $('.text-input').val('');
    // todo 向websocket发送请求
    console.info("向websocket发送请求")
    websocketSend(sendMessage, thisBubble);
    // 发消息后滚动到最底部
    $('.right-chatRoom').animate({scrollTop:$('.right-chatRoom').prop('scrollHeight')}, 'slow');
}

/**
 * 发送问题信息  由于增加时延，所以去掉颜色区分
 * */
/*function sendQuestion(sendMessage,roomName) {
    let user = $(".user-name").contents().filter(function () {
        return this.nodeType === 3; // 筛选文本节点
    }).text().trim();
    let email = $(".user-name").contents().filter(function () {
        return this.nodeType === 1; // 筛选element节点
    }).text().trim();
    let sendType = 'question';
    let file = '';
    let thisBubble = drawBubble('right', 'end', user, email, sendMessage, sendType, file)
    $('.text-input').val('');
    // todo 向websocket发送请求
    websocketSend(sendMessage, thisBubble);
    // 发消息后滚动到最底部
    $('.right-chatRoom').animate({scrollTop:$('.right-chatRoom').prop('scrollHeight')}, 'slow');
    // $('.right-chatRoom').scrollTop($('.right-chatRoom').prop('scrollHeight'));
    //发送完问题信息后  调用文心一言模型，生成回复
    WenXinModal(sendMessage,roomName);
}*/
/**
 * 更新文件信息
 * */
function ajaxFile(formData, bubbles) {
    let copyBubbles = bubbles.slice();
    $.ajax({
        url: '/uploadFile/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code) {
                if (res.code === 200) {
                    sendSuccess(bubbles[res.data]);
                    msgCount += 1;
                    $(selectedChatRoomDom).find('.chat-num').text(`${msgCount} 条对话`);
                } else {
                    sendError(bubbles[res.data]);
                }
                copyBubbles.splice(res.data, 1);
            } else {
                // 重定向到登录页
                window.location.href = '/loginPage';
            }

        },
        error: function () {
            copyBubbles.forEach(bubble => {
                sendError(bubble)
            })
        }
    });
}
/**
 * 发送文件
 * */
function sendFile() {
    let index = 0;
    let user = $(".user-name").contents().filter(function () {
        return this.nodeType === 3; // 筛选文本节点
    }).text().trim();
    let code = $(".user-name").contents().filter(function () {
        return this.nodeType === 1; // 筛选element节点
    }).text().trim();
    let bubbles = [];
    fileArray.forEach(file => {
        const reader = new FileReader();
        reader.onload = function (event) {
            if (file.type.indexOf("image") === 0) {
                bubbles.push(drawBubble('right', 'end', user, code, event.target.result, 'image', {name: file.name}));
            } else {
                bubbles.push(drawBubble('right', 'end', user, code, '../../static/img/unknown.png', 'others', file));
            }
            // 添加正在发送标志
            isSending(bubbles[index]);
            // 将文件添加到已发送文件数组中
            if (!sendFileArray.find(f => f.name === file.name && f.size === file.size)) {
                sendFileArray.push(file);
            }

            // todo ajax发送文件，发送成功去除正在发送标志，发送失败添加发送失败标志
            let formData = new FormData();
            formData.append('index', index);
            formData.append('file', file);
            formData.append('roomName', $('.right-title').text());
            // 发送文件
            ajaxFile(formData, bubbles)

            index++;
            // 发消息后滚动到最底部
            $('.right-chatRoom').animate({scrollTop:$('.right-chatRoom').prop('scrollHeight')}, 'slow');
            // $('.right-chatRoom').scrollTop($('.right-chatRoom').prop('scrollHeight'));
        };
        reader.readAsDataURL(file);
    });
    // 点击发送之后，将输入的文件清空
    fileArray = [];
    $('.file-input').empty();
    $('.file-input').removeClass("hide-file-input-before");
}

/**
 * 延迟时间
 * */
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 发送类型分拣
 * */
function send() {
    // 发送文字
    if ($('.send-img').hasClass('text')) {
        //获取信息
        let sendMessage = $('.text-input').val();
        if(sendMessage.length<1){
            alert("请不要发送空信息~");
        }else{
            //先直接发送信息
            sendMsg(sendMessage);
            //主题检测
            let roomName = $('.right-title').text();
            console.info("开始主题检测"+"房间名字："+roomName+"检测信息："+sendMessage);
            TopicDetection(sendMessage,roomName);
        }
        // 发送文件
    }else if ($('.send-img').hasClass('file')) {
        sendFile();
    }
}
/**
 * 点击发送图片 发送信息
 * */
$('.send-img').click(function () {
    send();
});
/**
 * 回车发送信息
 * */
$(document).on("keydown", "textarea", function(e) {
    // 取消默认回车换行改为消息发送，添加Ctrl+Enter组合键换行
    if ((e.keyCode === 13 && e.ctrlKey) || (e.keyCode === 13 && e.metaKey)) {
        e.preventDefault();
        var value = $(this).val();
        var start = this.selectionStart;
        var end = this.selectionEnd;
        $(this).val(value.slice(0, start) + "\n" + value.slice(end));
        this.selectionStart = this.selectionEnd = start + 1;
        changeTextareaHeight('.text-input');
    }else if (e.keyCode === 13) {
        e.preventDefault();
        send();
    }
});
/**
 * 自动填充艾特助手
 * */
$('#sendInput').on('input', function() {
    var inputValue = $(this).val(); // 获取textarea的当前值
    if(inputValue.length>2){
        var lastValue=inputValue[inputValue.length-1]+inputValue[inputValue.length-2];
        console.log('Textarea value:', lastValue); // 在控制台打印值
        //如果最后一个输入了@则自动填充文文
        if(lastValue==="@@"){
            $(this).val(inputValue+"文文");
        }else if(lastValue=="//"){
            $(this).val(inputValue.replace(new RegExp("@@文文//"),""));
        }
    }
});

/**
 * Endter发送
 * */
$(document).on('keydown', '.file-input', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        send();
    }
})

/**
 * 加载讨论室内容-小组基本信息
 * */
function queryChatRoomByName(fomDataChatRoom) {
    $.ajax({
        url:'selectChatRoom',
        type:'post',
        data:fomDataChatRoom,
        async: false,
        contentType: false,
        processData: false,
        success:function (res){
            if(res.code==200){
                console.log(res.data)
                console.log("获取的小组的内容++++")
                console.log("key"+res.data.contentKey);
                console.log("content"+res.data.content);
                console.log("item"+res.data.item);
                if(res.data!=null){
                    $('.add-text-item').text(res.data.item);
                    $('.add-text-content').text(res.data.content);
                    $('.add-text-key').text(res.data.contentKey);
                }
            }
        }
    })
}

/**
 * 加载讨论室内容-小组成员
 * */
function queryChatRoomUser(fomDataChatRoom) {
    $.ajax({
        url:'selectChatRoomUser',
        type:'post',
        data:fomDataChatRoom,
        async: false,
        contentType: false,
        processData: false,
        success:function (res){
            if(res.code==200){
                console.log(res.data)
                if(res.data!=null){
                    // 这里可以通过 item 访问每个对象的属性
                    console.log("新的成员列表"+res.data);
                    res.data.forEach(function(item) {
                        console.log(item.id);
                        console.log(item.name);
                        console.log(item.code);
                        $('.user-box').append(`<div class="user-item">
                                <div class="user-img"></div>
                                <div class="user-bottom">
                                    <div class="chat-title">${item.name}</div>
                                    <div class="chat-time">${item.code}</div>
                                </div>
                            </div>`);
                    });
                }
            }
        }
    })
}

/**
 * 加载聊天信息
 * */
function loadingMsg(formData, dom) {
    $.ajax({
        url: 'loadingMsg',
        type: 'post',
        data: formData,
        async: false,
        contentType: false,
        processData: false,
        success:function (res) {
            if (res.code === 200) {
                console.log(res.data)
                let allData = res.data;
                console.log("allData",allData);
                if (dom != null) {
                    $(dom).text(allData.total + ' 条对话');
                    // 获取当前聊天室消息数量
                    msgCount = parseInt(allData.total);
                }
                // 添加聊天气泡
                allData.list.forEach(data => {
                    if (data.msgType === 'text') {
                        drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, '');
                    }else if(data.msgType === "question"){
                        drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, '');
                    }else if(data.msgType === "answer"){
                        drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, '');
                    }else if (data.msgType === 'image') {
                        let fileInfo = {name: data.filename}
                        drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, fileInfo);
                    }else if (data.msgType === 'others') {
                        let fileInfo = {name: data.filename, size: data.filesize}
                        drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, fileInfo);
                    }
                });
            }else {
                console.info("添加气泡出现错误")
                // 重定向到登录页
                window.location.href = '/loginPage';
            }
        },
        error: function (res) {
            console.info("加载聊天信息出现错误")
            // 重定向到登录页
            window.location.href = '/loginPage';
        }

    })
}

/**
 * 加载聊天信息
 * */
function loadingAnswer(formData) {
    $.ajax({
        url: 'loadingAnswer',
        type: 'post',
        data: formData,
        async: false,
        contentType: false,
        processData: false,
        success:function (res) {
            if (res.code === 200) {
                console.log(res.data)
                let allData = res.data;
                // 添加聊天气泡
                allData.list.forEach(data => {
                    if(data.msgType === "question"){
                        console.info(data.content);
                        //drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, '');
                    }else if(data.msgType === "answer"){
                        console.info(data.content);
                        //drawBubble(data.position, 'head', data.username, data.sender, data.content, data.msgType, '');
                    }
                });
            }else {
                console.info("添加气泡出现错误")
                // 重定向到登录页
                window.location.href = '/loginPage';
            }
        },
        error: function (res) {
            console.info("加载聊天信息出现错误")
            // 重定向到登录页
            window.location.href = '/loginPage';
        }

    })
}

/**
 * 拉取信息
 * */
$('.right-chatRoom').scroll(function () {
    // todo 向后台拉取历史消息
    let roomName = $('.right-title').text();
    let formData = new FormData();
    // 添加前滚动条长度
    let beforeScrollLength = $(this).prop('scrollHeight');
    let allMsgNum = 0;
    if ($(this).scrollTop() === 0) {

        formData.append("pageIndex", msgPageIndex);
        formData.append("roomName", roomName);
        loadingMsg(formData, null);
        // 加载完一页之后自动跳转到下一页
        msgPageIndex++;

        // 添加后滚动条长度
        let afterScrollLength = $(this).prop('scrollHeight');
        // 将滚动条滚动到没添加前的位置
        $(this).scrollTop(afterScrollLength - beforeScrollLength)
    }
});


/**
 * 拉取回答信息信息
 * */
$('.analysis-box').scroll(function (roomName) {
    // todo 向后台拉取历史消息
    let formData = new FormData();
    // 添加前滚动条长度
    let beforeScrollLength = $(this).prop('scrollHeight');
    let allMsgNum = 0;
    if ($(this).scrollTop() === 0) {
        formData.append("pageIndex", msgPageIndex);
        formData.append("roomName", roomName);
        loadingMsg(formData, null);
        // 加载完一页之后自动跳转到下一页
        msgPageIndex++;

        // 添加后滚动条长度
        let afterScrollLength = $(this).prop('scrollHeight');
        // 将滚动条滚动到没添加前的位置
        $(this).scrollTop(afterScrollLength - beforeScrollLength)
    }
});

/**
 * 模拟接受websocket消息
 * */
function acceptMsg(res) {
    //聊天信息
    let dataJson = JSON.parse(res).data;
    // 添加前滚动条位置
    let beforeScrollLength = $('.right-chatRoom').scrollTop();
    // 更新消息数量
    msgCount++;
    $(selectedChatRoomDom).find('.chat-num').text(`${msgCount} 条对话`);
    // 通知提示
    suportNotify(dataJson.sender, dataJson.content, dataJson.type)
    // 绘制聊天气泡
    if (dataJson.type === 'text') {
        drawBubble('left', 'end', dataJson.username, dataJson.sender, dataJson.content, dataJson.type, '');
    }else if (dataJson.type === 'image') {
        drawBubble('left', 'end', dataJson.username, dataJson.sender, dataJson.content, dataJson.type, {name:dataJson.name});
    }else if(dataJson.type==='question'){
        drawBubble('left', 'end', dataJson.username, dataJson.sender, dataJson.content, dataJson.type, '')
    }else if(dataJson.type==='answer'){
        drawBubble('left', 'end', dataJson.username, dataJson.sender, dataJson.content, dataJson.type, '')
    } else if (dataJson.type === 'others') {
        let file = {name: dataJson.name, size: dataJson.size}
        drawBubble('left', 'end', dataJson.username, dataJson.sender, dataJson.content, dataJson.type, file);
    }
    // 添加后滚动条长度
    let afterScrollLength = $('.right-chatRoom').prop('scrollHeight');
    // 滚动范围较小将聚焦到底部
    if (afterScrollLength - beforeScrollLength < 1000) {
        $('.right-chatRoom').animate({scrollTop: afterScrollLength}, 'slow');
    }


}

$(document).on('click', '.bubble-file', function () {
    let downUrl = $(this).attr('name');
    let sp = 'alias='
    let encodeDownUrl = downUrl.split(sp)[0] + sp + encodeURIComponent(downUrl.split(sp)[1])
    window.open(encodeDownUrl, '_blank')
});


//判断浏览器是否支持Web Notifications API
function suportNotify(title, msg, type) {
    if (window.Notification) {
        // 支持
        console.log("支持" + "Web Notifications API");
        //如果支持Web Notifications API，再判断浏览器是否支持弹出实例
        showMess(title, msg, type)
    } else {
        // 不支持
        alert("不支持 Web Notifications API");
    }
}

//判断浏览器是否支持弹出实例
function showMess(title, msg, type) {
    console.log('1：' + Notification.permission);
    //如果支持window.Notification 并且 许可不是拒绝状态
    if (window.Notification && Notification.permission !== "denied") {
        //Notification.requestPermission这是一个静态方法，作用就是让浏览器出现是否允许通知的提示
        Notification.requestPermission(function (status) {
            console.log('2: ' + status);
            //如果状态是同意
            if (status === "granted") {
                let body = '';
                if (type === 'text') {
                    body = msg
                } else {
                    body = "【文件信息不支持预览，请点击跳回网页查看！！】"
                }
                var m = new Notification(`用户${title}发送一条信息`, {
                    body: body, //消息体内容
                    icon: "../static/img/notice.png", //消息图片
                    tag: "msg",
                    renotify: true,
                    timeout: 3000
                });
                // 延时3秒关闭
                setTimeout(function () {
                    m.close();
                }, 3000);
                m.onclick = function () { //点击当前消息提示框后，跳转到当前页面
                    window.focus();
                }
            } else {
                alert('当前浏览器不支持弹出消息')
            }
        });
    }
}

    /**
     * 修改用户密码
     * */
    function RevisePassword(password) {
        let code = $(".user-name").contents().filter(function () {
            return this.nodeType === 1; // 筛选element节点
        }).text().trim();
        let formData = new FormData();
        formData.append('code', code);
        formData.append('password', password);
        $.ajax({
            url: '/revise/',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.code === 200) {
                    cocoMessage.success(2000, res.data)
                    alert("修改密码成功");
                    window.location.href = '/loginPage';
                }else if(res.code === 201) {
                    cocoMessage.info(2000, res.data)
                }else {
                    alert("修改密码错误");
                }
                },
            error: function (res) {
                    // 重定向到登录页
                    window.location.href = '/loginPage';
                },
            })
}
